
package com.unc.allergyex;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.unc.allergyex.helpers.ObjManager;
import com.unc.allergyex.objects.MapRestaurant;
import com.unc.allergyex.objects.RestaurantItemizedOverlay;
import com.unc.allergyex.objects.RestaurantPin;
import com.unc.allergyex.objects.db.Restaurant;
import com.unc.allergyex.objects.db.RestaurantLocation;
import com.unc.allergyex.objects.tasks.MenuQueryTask;
/**
 * 
 * This is the activity for map disambiguation. 
 * It has a MapView and displays the location of a restaurant with a blue map pin.
 * This is the activity that is launched by Disambiguation when the user clicks
 * the button "show on map" for a restaurant.
 * The layout file is mapdisambig.xml.
 * 
 * @author Abigail
 */
public class MapDisambiguation extends MapActivity{
	private MapView mapView;
	private List<Overlay> mapOverlays;
	private MapController mc;
	private MenuQueryTask task;

	ArrayList<MapRestaurant> locations;

	/**
	 * Sets up MapDisambiguation activity.
	 * First checks for internet connectivity - if not connected, displays alert dialogue and does not complete laucnhing.
	 * If connected, dynamically creates zoom controls. Retrieves restaurants to display from ObjectManager.
	 * Calls the displayLocations method, then animates the map to the first element in the locations array.
	 * 
	 * @author Abigail
	 * @see com.google.android.maps.MapActivity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mapdisambig);
		if (isOnline() == false){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("AllergyEx can't connect to the internet. Please ensure you have network connectivity.");
			builder.setCancelable(false);
			builder.setPositiveButton("Okay", null);
			AlertDialog alert = builder.create();
			alert.show();
		}
		else{
			mapView = (MapView) findViewById(R.id.mapviewdisambig);

			//Setting zoom controls
			ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);
			zoomControls.setOnZoomInClickListener(new OnClickListener() {
				public void onClick(View v) {
					mapView.getController().zoomIn();
				}
			});
			zoomControls.setOnZoomOutClickListener(new OnClickListener() {
				public void onClick(View v) {
					mapView.getController().zoomOut();
				}
			});

			mc = mapView.getController();
			mapOverlays = mapView.getOverlays();

			Restaurant[] curr_restaurants = ObjManager.getMapSearchRestaurantList();
			locations = new ArrayList<MapRestaurant>();
			for (Restaurant r : curr_restaurants){
				for (RestaurantLocation l : r.getLocations()){
					MapRestaurant current = new MapRestaurant(r.getId(), 
							r.getName(), 
							l.getAddress(), 
							l.getLatitude(), 
							l.getLongitude(),
							l.getPhone());
					locations.add(current);
				}
			}

			displayLocations();
			int curr_lat = (int) (locations.get(0).getLat());
			int curr_lon = (int) (locations.get(0).getLon());
			GeoPoint curr_point = new GeoPoint(curr_lat, curr_lon);
			mc.animateTo(curr_point);
			mc.setZoom(17);
		}
	}

	/**
	 * This method executes a menu query for the restaurant that has been selected.
	 * It is launched when the forward arrow is tapped on the restaurant pin's popup balloon.
	 * 
	 * @param v the balloon that contains the button that is being tapped
	 */
	public void restaurantSelected (View v){
		//This method launches the results screen when the forward arrow in the balloon is clicked
		View vc = ((ViewGroup)v.getParent()).findViewById(R.id.restaurantId);
		String id = ((TextView)vc).getText().toString();

		task = new MenuQueryTask();
		task.setContext(this);
		task.execute(id);
	}
	
	
	/**
	 * This method adds all locations to be displayed to RestaurantItemizedOverlay overlay and then adds
	 * these overlays to a list of of overlays called mapOverlays.
	 */
	public void displayLocations(){
		//This method adds a restaurant pin to the map for each restaurant
		for (MapRestaurant location : locations){			
			Drawable icon = getResources().getDrawable(R.drawable.mappinblue);
			int w = icon.getIntrinsicWidth();
			int h = icon.getIntrinsicHeight();
			icon.setBounds(-w / 2, -h, w / 2, 0);

			GeoPoint curr_point = new GeoPoint((int)(location.getLat()), (int)(location.getLon()));
			RestaurantPin item = new RestaurantPin(curr_point, "", "", location);
			RestaurantItemizedOverlay itov = new RestaurantItemizedOverlay(icon, mapView, this);

			item.setMarker(icon);
			itov.addOverlay(item);
			mapOverlays.add(itov);

		}
	}

	/** 
	 * Required method for all MapActivities. We aren't using it.
	 * 
	 * @see com.google.android.maps.MapActivity#isRouteDisplayed()
	 */
	@Override
	protected boolean isRouteDisplayed() {
		//Stub method required for all map activities
		return false;
	}
	
	/**
	 * Back button that finishes the activity
	 * 
	 * @param v default param for this method
	 */
	public void returnButtonClicked(View v){
		//Built in back button method
		this.finish();
	}
	
	/**
	 * Checks to see if device has Internet connectivity.
	 * Requires ACCESS_NETWORK_STATE permission in manifest file
	 * 
	 * @return boolean value indicating online status
	 */
	private boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	/**cancel the query task when the activity is paused
	 * @see android.app.Activity#onPause()
	 */
	@Override
	public void onPause(){
		super.onPause();
		cancelTask();
	}
	
	/**cancel the query task when the activity is destroyed
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	public void onDestroy(){
		super.onDestroy();
		cancelTask();
	}
	
	/**cancel the query task if it is not null
	 * 
	 */
	private void cancelTask(){
		if (task != null){
			task.cancel(true);
		}
	}
}


